﻿using PLCS.Application.Contracts.HisTaskApp.Dtos;
using PLCS.Application.Contracts.TaskApp;
using PLCS.Application.Contracts.TaskApp.Dtos;
using PLCS.Domain.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;

namespace PLCS.Application.TaskApp;

public class InstructionAppService : CrudAppService<Instruction, InstructionDto, Guid, PagedResultRequestDto, InstructionEditDto>, IInstructionAppService
{
    private readonly IInstructionRepository _repository;

    public InstructionAppService(IInstructionRepository repository) : base(repository)
    {
        this._repository = repository;
    }

    public async Task AgainIssuedAsync(Guid Id)
    {
        await _repository.ChangeStatusAsync(Id, Domain.Shared.Tasks.InstructionStatus.未执行);
    }

    public async Task ChangeStatusAsync(Guid Id, Domain.Shared.Tasks.InstructionStatus taskStatus)
    {
        var entity = await Repository.GetAsync(Id);
        entity.ChangeStatus(taskStatus);
        await Repository.UpdateAsync(entity);
    }

    public async Task FinshTaskAsync(Guid Id)
    {
        await _repository.ChangeStatusAsync(Id, Domain.Shared.Tasks.InstructionStatus.已完成);
    }

    public async Task<PagedResultDto<InstructionDto>> GetListBySearchAsync(PagedResultRequestDto input, string? instructionNo, string? equipmentNo, string? status)
    {
        await CheckGetListPolicyAsync();

        var query = await CreateFilteredQueryAsync(input);

        bool isInstructionNo = int.TryParse(instructionNo, out int intInstructionNo);
        query = query.WhereIf(isInstructionNo, x => x.InstructionNo == intInstructionNo)
            .WhereIf(!string.IsNullOrEmpty(equipmentNo), x => x.EquipmentNo == equipmentNo)
            .WhereIf(!string.IsNullOrEmpty(status), x => x.Status == (Domain.Shared.Tasks.InstructionStatus)Enum.Parse(typeof(Domain.Shared.Tasks.InstructionStatus), status))
            .OrderByDescending(x => x.CreationTime);
        var totalCount = await AsyncExecuter.CountAsync(query);

        query = ApplySorting(query, input);
        query = ApplyPaging(query, input);

        var entities = await AsyncExecuter.ToListAsync(query);
        var entityDtos = await MapToGetListOutputDtosAsync(entities);

        return new PagedResultDto<InstructionDto>(
            totalCount,
            entityDtos
        );
    }
}